package org.geektimes.projects.user.web.controller;

import org.eclipse.microprofile.config.Config;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.projects.user.validator.bean.validation.DelegatingValidator;
import org.geektimes.web.env.ConfigHolder;
import org.geektimes.web.mvc.controller.PageController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * @author tom
 * @since 2021/3/2 14:35
 */
@Path("register")
public class RegisterController implements PageController {

    private static final Logger log = Logger.getLogger(RegisterController.class.getName());

    @Resource(name = "bean/Validator")
    private DelegatingValidator delegatingValidator;

    @Resource(name = "bean/UserService")
    private UserService userService;

    @GET
    @Path("")
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        Config config = ConfigHolder.getConfig();
        request.setAttribute("applicationName", config.getValue("application.name", String.class));
        return "register.jsp";
    }

    @POST
    @Path("")
    public String doRegister(HttpServletRequest request, HttpServletResponse response){
        User user = new User();
        user.setName(request.getParameter("name"));
        user.setPassword(request.getParameter("password"));
        user.setPhoneNumber(request.getParameter("phoneNumber"));
        user.setEmail(request.getParameter("email"));

        //数据效验
        Set<ConstraintViolation<User>> violations = delegatingValidator.validate(user);
        if(null != violations && violations.size() > 0){
            List<String> errors = violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
            //记录效验失败日志
            errors.forEach(log::warning);
            request.setAttribute("errors", errors);
            return "fail.jsp";
        }

        //数据效验通过
        boolean result = userService.register(user);
        if(result){
            return "success.jsp";
        }else{
            return "fail.jsp";
        }
    }
}
